//! Zenop2p 专用流协议：定义 zenoh 数据传输的 libp2p 协议
use libp2p::core::upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p::swarm::{Stream, StreamProtocol};
use std::iter::Once;

/// Zenop2p 流协议标识（唯一区分其他协议）
pub const ZENOP2P_PROTOCOL: StreamProtocol = StreamProtocol::new("/zenop2p/stream/1.0.0");

/// 协议升级器：协商创建 Zenop2p 专用流
#[derive(Debug, Clone, Default)]
pub struct Zenop2pProtocolUpgrade;

/// 实现 UpgradeInfo：声明支持的协议
impl UpgradeInfo for Zenop2pProtocolUpgrade {
    type Info = StreamProtocol;
    type InfoIter = Once<Self::Info>;

    fn protocol_info(&self) -> Self::InfoIter {
        std::iter::once(ZENOP2P_PROTOCOL)
    }
}

/// 实现 InboundUpgrade：处理入站流请求
impl InboundUpgrade<Stream> for Zenop2pProtocolUpgrade {
    type Output = Stream;
    type Error = std::convert::Infallible;
    type Future = futures::future::Ready<Result<Self::Output, Self::Error>>;

    fn upgrade_inbound(self, stream: Stream, _: Self::Info) -> Self::Future {
        futures::future::ready(Ok(stream))
    }
}

/// 实现 OutboundUpgrade：发起出站流请求
impl OutboundUpgrade<Stream> for Zenop2pProtocolUpgrade {
    type Output = Stream;
    type Error = std::convert::Infallible;
    type Future = futures::future::Ready<Result<Self::Output, Self::Error>>;

    fn upgrade_outbound(self, stream: Stream, _: Self::Info) -> Self::Future {
        futures::future::ready(Ok(stream))
    }
}